package com.study.clothes.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.clothes.pojo.RespBean;
import com.study.clothes.pojo.User;
import com.study.clothes.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private JavaMailSender javaMailSender;

    private String from="JerryKB2585@163.com";
    @GetMapping("/")
    public User login(User user, HttpServletRequest request) {
        System.out.println(user);
        List<User> list = iUserService.list();
        for (User user1 : list) {
            if (user1.getUsername().equals(user.getUsername()) && user1.getPassword().equals(user.getPassword())) {
                user1.setPassword("");
                request.getServletContext().setAttribute("userInfo", user1);
                return user1;
            }

        }
        return null;

    }
    @PostMapping("/")
    public RespBean register(User user){
        List<User> list = iUserService.list();
        for (User user1 : list) {

            if (user1.getEMail().equals(user.getEMail())){
                return RespBean.error("该邮箱已注册");
            }
            if (user1.getUsername().equals(user.getUsername())) {
                return RespBean.error("用户名已注册");
            }
        }

        if (iUserService.save(user)){
            return RespBean.success("注册成功",user);
        }
        return RespBean.error("其他异常，请联系管理员");
    }
    @GetMapping("/getCode")
    public String getCode( String eMail){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setSubject("韩都衣舍");

        int code = (int) ((Math.random() +1)* 1000)+1;
        simpleMailMessage.setText("您正在注册韩都衣舍电商平台账号，验证码是："+code +"，请及时输入。");
        simpleMailMessage.setTo(eMail);
        System.out.println(code);

        javaMailSender.send(simpleMailMessage);
        return String.valueOf(code);


    }


}
